package ext.acae2.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class RemoveNSUtil {

	public static String remove(String path) throws DocumentException,
			IOException {
		File file = new File(path);
		SAXReader reader = new SAXReader();
		Document doc = reader.read(file);

		String str = doc.asXML();
		String ns = "http://www.plmxml.org/Schemas/PLMXMLSchema";
		int beginIndex = str.indexOf(ns);
		int endIndex = beginIndex + ns.length();

		String newPath = path;
		
		if(beginIndex != -1){
			String tempStr = str.substring(0, beginIndex) + str.substring(endIndex);
			Document tempDoc = DocumentHelper.parseText(tempStr);

			newPath = path.replace(".xml", "_new.xml");
			OutputStream os = new FileOutputStream(newPath);
			OutputFormat format = OutputFormat.createCompactFormat();
			format.setEncoding("utf-8");

			XMLWriter writer = new XMLWriter(os, format);
			writer.write(tempDoc);
			writer.close();
		}
		
		return newPath;
	}

}
